package com.fm.controller;

import com.fm.dto.LoginForm;
import com.fm.entity.User;
import com.fm.service.UserService;
import com.fm.utils.KeyUtils;
import com.fm.utils.R;
import com.fm.utils.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/8/2 0002.
 */
@RestController
@RequestMapping("/api")
public class IndexController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "account")
    @ResponseBody
    public R login(@RequestBody LoginForm form, HttpServletRequest request){
        try{
            User user = userService.getByUserName(form.getUserName());
            Map remap = new HashMap();
            if (user == null) {
                remap.put("status", "error");
            } else if (!form.getPassword().equals(user.getPassword())){
                remap.put("status", "error");
            }else {
                SessionUtil.setLoginUser(user);
                remap.put("status", "ok");
                String token = KeyUtils.getRandonString(11);
                remap.put("token", token);
                SessionUtil.setSessionAttribute("TOKEN", token);
            }
            remap.put("type", form.getType());
            remap.put("currentAuthority", "admin");
            return R.ok().put("data", remap);
        }catch(DataAccessException da){
            throw new RuntimeException(da.getRootCause().getMessage());
        }
    }
}
